package game
{
	import assets.Asset;
	
	import controller.MapCameraController;
	
	import events.LoadedEvent;
	
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.Dictionary;
	
	import gameObject.CitadelMap;
	import gameObject.User;
	
	import tool.BitmapTool;
	
	public class Citadel extends Sprite
	{
		private var _map:CitadelMap;
		
		private var _xmlURL:String = Global.assetPath+"UI/jjzb_scbar.xml";
		private var _xmlLoader:URLLoader;
		private var _bmdLoader:Loader;
		private var _xml:XML;
		private var _bitmapURL:String;
		
		private var _bitmapDatas:Dictionary;
		
		public function Citadel()
		{
			_map = new CitadelMap;
			_map.addEventListener(Event.CLOSE,onClose);
			_map.addEventListener(Event.COMPLETE,onMapLoadec);
		}
		
		private function onClose(e:Event):void
		{
			if(parent)parent.removeChild(this);
			if(_map.controller)_map.controller.dispose();
			if(Global.gameView.camera.parent)Global.gameView.camera.parent.removeChild(Global.gameView.camera);
			
			_map.removeEventListener(Event.CLOSE,onClose);
		}
		
		private function onMapLoadec(e:Event):void
		{
			_map.removeEventListener(Event.COMPLETE,onMapLoadec);
			
			var con:MapCameraController = new MapCameraController;
			_map.controller = con;
			con.mouseRotateCamera();
			
			_xmlLoader = new URLLoader;//取ui美术资源
			_xmlLoader.addEventListener(Event.COMPLETE,xmlLoaded);
			_xmlLoader.load(new URLRequest(_xmlURL));
		}
		
		private function xmlLoaded(e:Event):void
		{
			_xmlLoader.removeEventListener(Event.COMPLETE,xmlLoaded);
			_xml = new XML(_xmlLoader.data);
			
			_bitmapURL = Global.assetPath+_xml.bitmaps.@ima;
			
			Asset.bitmapdata.addEventListener(LoadedEvent.BITMAPDATA_COMPLETE,bmdLoaded);
			Asset.bitmapdata.load(_bitmapURL);
		}
		
		private function bmdLoaded(e:LoadedEvent):void
		{
			if(e.URL==_bitmapURL)
			{
				Asset.bitmapdata.removeEventListener(LoadedEvent.BITMAPDATA_COMPLETE,bmdLoaded);
				var bmd:BitmapData = Asset.resBitmapDatas[_bitmapURL];
				_bitmapDatas = BitmapTool.cutImageUseXML(bmd,new XML(_xml.bitmaps));
				
				Global.gameView.scene.addChild(_map);
				addChild(Global.user);
				Global.user.dispayInfo(_bitmapDatas);
			}
		}
		
	}
}